package co.fitstart.market.handler.impl;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.demo2do.core.support.Result;

import co.fitstart.market.handler.JinjiaHandler;

/**
 * 
 * @author mohanlan
 *
 */
@Component("jinjiaHandler")
public class JinjiaHandlerImpl implements JinjiaHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(JinjiaHandlerImpl.class);
	
	public static final String optId = "b5203RMJ20180208";
	
	public static final String url = "http://mobile.b52.jinjiamedia.com/b52-mobile-gateway/regist/asynProc";
	
	//public static final String url = "http://http.test.jinjiajinrong.com/b52-mobile-gateway/regist/asynProc";
		
	/*
	 * (non-Javadoc)
	 * @see co.fitstart.market.handler.JinjiaHandler#onRegiste(java.lang.String, java.lang.String, java.lang.Long, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public Result onRegiste(String serailNumber, String userName, Long userId, String registeResult) {
		
		Result result = new Result();
		
		logger.trace("JinjiaHandlerImpl#onRegiste() - start registe with userId [{}] userName [{}] result [{}].", userId, userName, registeResult);
		
		try {
			
			Response response = Request.Post(new URIBuilder(url)
												 .build()
							 	)
								.connectTimeout(10000)
								.socketTimeout(1000)
								.bodyForm(Form.form()
											  .add("serailNumber", serailNumber)
											  .add("userId", String.valueOf(userId))
											  .add("username", userName)
											  .add("optId", optId)
											  .add("result", registeResult)
											  .build())
								.execute();
			
			String body = response.returnContent().asString(Consts.UTF_8);
            logger.trace("JinjiaHandlerImpl#onRegiste() - Get response body [{}].", body);
            
            Map<String, Object> data = JSON.parseObject(body, Map.class);
            String errcode = data.get("code").toString();
            String errmsg = (String) data.get("msg");
            
            if (StringUtils.equalsIgnoreCase(errcode, "0000")) {
                logger.error("JinjiaHandlerImpl#onRegiste() - Sending message occurs error. The error code is [{}] and error message is [{}].", errcode, errmsg);
                result.success().message(errmsg).data(data);  // Put invalid userid, party, tag into data
            }else {
            	result.fail().message(errmsg).data(data);
            }
			
		} catch (URISyntaxException use) {
            logger.error("JinjiaHandlerImpl#onRegiste() - URI builder encounters syntax exception: {}", use);
        } catch (IOException ie) {
        	logger.error("JinjiaHandlerImpl#onRegiste() - registe encounters IO exception: {}", ie);
        }
		
		return result;
	}

}
